package com.example.springboot.service;

import com.example.springboot.common.Page;
import com.example.springboot.demos.web.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
@Autowired
    UserMapper userMapper;
    /*public void insertUser(User user) {
        userMapper.insert(user);
        // 你的插入逻辑
    }*/
   public void insertUser(com.example.springboot.entity.User user) {
           userMapper.insert(user);

  }
  public void updateUser(com.example.springboot.entity.User user) {
       userMapper.updateUser(user);
  }

    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }

    public void batchDeleteUser(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteUser(id);  // 7  - 8
        }
    }

    public List<User> selectAll() {
       return userMapper.selectAll();
    }

    public com.example.springboot.entity.User selectById(Integer id) {
        return userMapper.selectById(id);
    }
    public List<com.example.springboot.entity.User> selectByName(String name) {
        return userMapper.selectByName(name);
    }


    public List<com.example.springboot.entity.User> selectByMore(String username, String name) {
        return userMapper.selectByMore(username,name);
    }
    public List<com.example.springboot.entity.User> selectByMo(String username, String name) {
       return userMapper.selectByMo(username,name);
    }

    public Page<User> selectByPage(Integer pageNum, Integer pageSize, String username, String name) {
        Integer skipNum = (pageNum - 1) * pageSize;  // 计算出来  1 -> 0,5    2 -> 5,5   3 -> 10,5

        Page<User> page = new Page<>();
        List<User> userList = userMapper.selectByPage(skipNum, pageSize, username, name);
        Integer total = userMapper.selectCountByPage(username, name);
        page.setTotal(total);
        page.setList(userList);
        return page;
    }
//验证用户账号是否合法
    public com.example.springboot.entity.User login(com.example.springboot.entity.User user) {
      //根据用户名查询数据库的用户信息
       com.example.springboot.entity.User dbUser = userMapper.selectUsername(user.getUsername());
       if (dbUser == null) {
           //  抛出一个自定义的异常
           throw new ServiceException("用户名或密码错误");
       }
      if (!user.getPassword().equals(dbUser.getPassword())) {
          throw new ServiceException("用户名或密码错误");
      }
       return dbUser;

    }
}